﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;
using Microsoft.Office.Server.Search.Query;
using System.Data;
using System.Diagnostics;
using System.Web.UI.WebControls;
using Microsoft.Office.Server;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

namespace SPDEV.Search.Utilities
{
    /// <summary>
    /// This page allows simple property based search, within the SSP associated with a given site collection
    /// </summary>
    public class SearchContentByPropertyAdminLayoutsPage :  LayoutsPageBase
    {
        // controls
        protected SPGridView gridView;
        protected TextBox SearchFieldTextBox;
        protected DropDownList AllManagedPropertiesDropDown;
        protected DropDownList AllSitesDropDown;
        protected Button DoSearchButton;

        // ivars
        private string FieldName { get; set; }
        private string SearchTerm { get; set; }
        private SPSite CurrentSite { get; set; }

        #region Ctrs / Init

        /// <summary>
        /// Useful for testing
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="searchTerm"></param>
        /// <param name="contextSite"></param>
        public SearchContentByPropertyAdminLayoutsPage(string fieldName, string searchTerm, SPSite contextSite)
        {
            this.FieldName = fieldName;
            this.SearchTerm = searchTerm;
            this.CurrentSite = contextSite;
        }

        public SearchContentByPropertyAdminLayoutsPage()
            : base()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.CurrentSite = SPContext.Current.Site;

            // add managed properties
            using (FullTextSqlQuery query = new FullTextSqlQuery(ServerContext.GetContext(this.CurrentSite)))
            {
                var listItems = query.GetProperties().Select(x => new ListItem(x.Name));
                AllManagedPropertiesDropDown.Items.AddRange(listItems.ToArray());

                string currentProperty = HttpContext.Current.Request.QueryString["Property"];
                if (string.IsNullOrEmpty(currentProperty))
                    currentProperty = "Title";

                AllManagedPropertiesDropDown.Items.FindByText(currentProperty).Selected = true;
            }

            // add all site collections
            var webApps = SPWebService.ContentService.WebApplications;
            foreach (var webApp in webApps)
            {
                foreach (SPSite site in webApp.Sites)
                {
                    AllSitesDropDown.Items.Add(new ListItem(site.Url));
                    site.Dispose();
                }
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.SearchTerm = this.SearchFieldTextBox.Text;
            this.FieldName = this.AllManagedPropertiesDropDown.SelectedValue;
            
            if (string.IsNullOrEmpty(this.FieldName))
                this.FieldName = "Title";
            
            if (!string.IsNullOrEmpty(this.SearchTerm))
            {
                using (SPSite scopedSite = new SPSite(AllSitesDropDown.SelectedValue))
                {
                    DataTable dataTable = GenerateDataTableOfResults(scopedSite);
                    gridView.DataSource = dataTable;
                    gridView.DataBind();
                }
            }
        }

        #endregion

        /// <summary>
        /// Generate results
        /// </summary>
        /// <param name="searchScopeSite"></param>
        /// <returns></returns>
        public DataTable GenerateDataTableOfResults(SPSite searchScopeSite)
        {
            // elevated site

            DataTable dataTable = null;
            using (FullTextSqlQuery query = new FullTextSqlQuery(Microsoft.Office.Server.ServerContext.GetContext(searchScopeSite)))
            {
                query.QueryText = string.Format("select Title, URL from scope() where freetext({0}, '{1}')", this.FieldName, this.SearchTerm);
                query.ResultTypes = ResultType.RelevantResults; // maybe
                query.AuthenticationType = QueryAuthenticationType.NtAuthenticatedQuery;
                query.TrimDuplicates = true;
                query.KeywordInclusion = KeywordInclusion.AllKeywords;
                query.SiteContext = new Uri(searchScopeSite.Url);
                query.RowLimit = 20;
                
                var resultTypes = query.Execute();
                var results = resultTypes[ResultType.RelevantResults];

                dataTable = new DataTable();
                dataTable.Load(results, LoadOption.OverwriteChanges);

            }
            return dataTable;
        }
    }
}
